// ** Copyright (c) 2011* Freiburg, Germany * All rights reserved.
// ** File name：Number.cpp
// ** Current version：1.0 * Author：Yongkang Zhong * Finish time：22.05.2011
// ** Replace version：1.0 * Original author: Yongkang Zhong * Finish time：22.05.2011

//#include <iostream>
#include <cstdlib>
#include "Calculator.h"

using namespace std;

extern const int MAX;

// The Function number recognizes a number in a string.
double number(char *str, int &index)
{
    char numStr[MAX];
    int i = 0;
    double value = 0.0;
    
    // determines if the current char is a digit or a point. If not, prints the error infos and quit the program.
    if (!isdigit(str[index]) && str[index] != '.')
    {
        cerr << "*** The format of expression is wrong." << " >> "; 
        cerr << index + 1 << ": \""<< str[index] << "\" >> Error(2) ***" << endl;
        exit(1);      
    }
    
    while(true)
    {
        if (isdigit(str[index]))
            numStr[i++] = str[index++];
        else if (str[index] == '.')
        {
            numStr[i++] = str[index++];
            
            // determines if the next char is a digit. If not, prints the error infos and quit the program.
            if (!isdigit(str[index]))
            {
                cerr << "*** The format of expression is wrong." << " >> "; 
                cerr << index + 1 << ": \""<< str[index] << "\" >> Error(3) ***" << endl;
                exit(1);              
            }
        }
        else
        {
            numStr[i] = '\0';
            break;
        }
    }
    
    value = atof(numStr);
    
    return value;
}
